import {Http,Response} from '@angular/http'

import {Injectable} from "@angular/core";
import {Category} from "../entity/Category";
import {ProjectCategory} from "../entity/ProjectCategory";
import {CommonIp} from "../../user/entity/Ip";
@Injectable()
export class CategoryFindService extends CommonIp{

  private categoryListDataURL=this.userIp+"/p/category/categoryTreeData?module=article";

  private categoryListURL =this.userIp+"/p/category/categoryList/article";

  private categoryFindByParentId = this.userIp+"/p/category/findByParentId/";
  constructor(public http:Http){
    super();
  }

  public findCategoryTreeData():Promise<Category[]>{
    return this.http.get(this.categoryListDataURL)
      .toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }
  private extractData(res:Response){
    if(res.status<200||res.status>=300){
      throw new Error('Bad response status:'+res.status);
    }

    let body  = res.json();
    sessionStorage.setItem("categoryList",JSON.stringify(body));
    return body||{};
  }
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
  public findAllCategory():Promise<ProjectCategory[]> {
    return this.http.get(this.categoryListURL)
      .toPromise().then(this.extractData).catch(this.handleError);
  }

  public findByParendId(categoryId: string):Promise<ProjectCategory[]> {
    return this.http.get(this.categoryFindByParentId+categoryId)
      .toPromise().then(this.extractfindByParentData).catch(this.handleError);
  }
  private extractfindByParentData(res:Response){
    if(res.status<200||res.status>=300){
      throw new Error('Bad response status:'+res.status);
    }

    let body  = res.json();
    sessionStorage.setItem("categoryList",JSON.stringify(body));
    return body.list||{};
  }
}
